package com.xbongbong.helper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.enums.FailureStrategy;
import com.xbongbong.enums.Priority;
import com.xbongbong.enums.ReleaseState;
import com.xbongbong.enums.Status;
import com.xbongbong.enums.WarningType;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.util.HeaderUtil;
import com.xbongbong.util.HttpRequestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 定时操作，一定要保证工作流上线才能进行定时操作
 * @ClassName SchedulerHelper
 * @Author 梁鲁江
 * 创建时间 2022/6/27 14:31
 * 修改时间  2022/6/27 14:31
 **/
@Component
public class SchedulerHelper {
    private static final Log log = LogFactory.getLog(SchedulerHelper.class);
    public  Integer insertSchedule(
            long projectCode,
            long processDefinitionCode,
            String schedule,
            WarningType warningType,
            int warningGroupId,
            FailureStrategy failureStrategy,
            Priority processInstancePriority,
            String workerGroup,
            Long environmentCode) throws XbbException {
        String url = HeaderUtil.getHosts()+"/dolphinscheduler/projects/" +
                projectCode +
                "/schedules";
        JSONObject requestData = new JSONObject();
        requestData.put("processDefinitionCode", processDefinitionCode);
        requestData.put("schedule", schedule);
        requestData.put("warningType", warningType.getUpDescp());
        requestData.put("warningGroupId", warningGroupId);
        requestData.put("failureStrategy", failureStrategy.getUpDescp());
        requestData.put("processInstancePriority", processInstancePriority.getUpDescp());
        requestData.put("workerGroup", workerGroup);
        requestData.put("environmentCode", environmentCode);
        String ret = HttpRequestUtils.post(url, requestData);
        JSONObject result = JSON.parseObject(ret);
        Integer code = result.getInteger("code");
        System.out.println(ret);
        if(Objects.equals(code, Status.SUCCESS.getCode())){
            return result.getJSONObject("data").getInteger("id");
        }else {
            log.error(ErrorCodeEnum.API_ERROR_263001);
            throw  new XbbException(ErrorCodeEnum.API_ERROR_263001);
        }
    }
    
    public  Integer insertSchedule(
            long projectCode,
            long processDefineCode,
            String schedule,
            int warningTypeCode,
            int warningGroupId,
            int failureStrategyCode,
            int processInstancePriorityCode,
            String workerGroup,
            Long environmentCode) throws XbbException {
        WarningType warningType = WarningType.getEnum(warningTypeCode);
        FailureStrategy failureStrategy = FailureStrategy.getEnum(failureStrategyCode);
        Priority processInstancePriority = Priority.getEnum(processInstancePriorityCode);
        return insertSchedule(projectCode,
                processDefineCode,
                schedule,
                warningType,
                warningGroupId,
                failureStrategy,
                processInstancePriority,
                workerGroup,
                environmentCode);
    }

    public  Integer insertSchedule(long projectCode, long processDefineCode, String schedule) throws XbbException {
        return insertSchedule(projectCode,
                processDefineCode,
                schedule,
                WarningType.NONE,
                0,
                FailureStrategy.CONTINUE,
                Priority.MEDIUM,
                "default",
                -1L);
    }

    /**
     * 设置上下线
     * @param projectCode
     * @param id
     * @param scheduleStatus
     * @return
     */
    public  String setScheduleState(
            long projectCode,
            Integer id,
            ReleaseState scheduleStatus) {
        String url = HeaderUtil.getHosts()+"/dolphinscheduler/projects/" +
                projectCode +
                "/schedules/"+ id +"/"+ scheduleStatus.getDescp();
        JSONObject requestData = new JSONObject();
        requestData.put("id",id);
        String ret = HttpRequestUtils.post(url, requestData);
        JSONObject result = JSON.parseObject(ret);
        Integer code = result.getInteger("code");
        if(Objects.equals(code, Status.SUCCESS.getCode())){

        }else {

        }
        System.out.println(ret);
        return "";
    }
    public  String setScheduleState(
            long projectCode,
            Integer id,
            int scheduleStatuCode) {
        return setScheduleState(projectCode,id, Objects.requireNonNull(ReleaseState.getEnum(scheduleStatuCode)));
    }

    /**
     * 删除定时任务 只能删除下线的
     * @param projectCode
     * @param code
     * @return
     */
    public static Long delete(long projectCode,long code){
        String url = HeaderUtil.getHosts()+"/dolphinscheduler/projects/"+projectCode+"/schedules/"+code;
        //参数格式要求  description=description&projectName=projectName
        String ret = HttpRequestUtils.delete(HeaderUtil.getHeader(), url);
        JSONObject result = JSON.parseObject(ret);
        Integer resultCode = result.getInteger("code");
        return 0L;
    }

    public static String updateSchedule(
            long projectCode,
            long id,
            String scheduleExpression,
            WarningType warningType,
            int warningGroupId,
            FailureStrategy failureStrategy,
            Priority processInstancePriority,
            String workerGroup,
            Long environmentCode) {
        String url = HeaderUtil.getHosts()+"/dolphinscheduler/projects/" +
                projectCode +
                "/schedules/"+ id ;
        JSONObject requestData = new JSONObject();
        requestData.put("schedule", scheduleExpression);
        requestData.put("warningType", warningType.getUpDescp());
        requestData.put("warningGroupId", warningGroupId);
        requestData.put("failureStrategy", failureStrategy.getUpDescp());
        requestData.put("processInstancePriority", processInstancePriority.getUpDescp());
        requestData.put("workerGroup", workerGroup);
        requestData.put("environmentCode", environmentCode);
        String ret = HttpRequestUtils.put(url, requestData);
        System.out.println(ret);
        return "";
    }

    public static String updateSchedule(
            long projectCode,
            long id,
            String scheduleExpression
    ) {
        return updateSchedule(projectCode, id, scheduleExpression,
                WarningType.NONE,
                0,
                FailureStrategy.CONTINUE,
                Priority.MEDIUM, "default",
                -1L);
    }


    public static void main(String[] args) throws XbbException {
//        insertSchedule(5959113343520L,5959113474848L,"{\"startTime\":\"2022-06-27 00:00:00\",\"endTime\":\"2122-06-27 00:00:00\",\"crontab\":\"* * * * * ? *\",\"timezoneId\":\"Asia/Shanghai\"}");
//        setScheduleState(5959113343520L,13,1);
//        setScheduleState(5959113343520L,13,0);
//        delete(5959113343520L,14L);
        updateSchedule(5959113343520L,15L,"{\"startTime\":\"2022-06-27 00:00:00\",\"endTime\":\"2122-06-27 00:00:00\",\"crontab\":\"* * * * * ? *\",\"timezoneId\":\"Asia/Shanghai\"}");
    }
}
